/**
 * 基于fetch封装的请求方法
 */
import ky from "ky"
import type { Options } from "ky"

import { getUserInfo } from "~utils/tools"

// 请求前拦截hook: 将验证Token注入header
const reqHeaderHook = async (request: Request) => {
  // 获取用户的请求token
  const token = await getUserInfo("authorization")
  // 设置headers
  if (token) {
    request.headers.set("Authorization", `JWT ${token}`)
  }
}

// 定义request方法参数定义
type RequestParams = {
  baseUrl?: string
  url: string
  method?: string
  options?: Options
}

const request = async <T = { [key: string]: any }>(
  params: RequestParams
): Promise<T> => {
  const { baseUrl, url, method, options } = params
  // url处理
  let requestUrl = url
  // 判断当前环境是否为开发环境
  const isDev = process.env.NODE_ENV === "development"
  // 如果不是开发环境，需要将url中包含v2/xx的部分，替换为v2_xxx
  // 如 ***/v2/test/***, 替换为 ***/v2_test/***
  if (!isDev) {
    requestUrl = url.replace(/v2\//g, "v2_")
  }
  // 构建ky请求配置
  const RequestMethod = method || "GET"
  const KyOptions: Options = {
    prefixUrl: baseUrl || process.env.PLASMO_PUBLIC_API_BASE_URL,
    method: RequestMethod,
    hooks: {
      beforeRequest: [reqHeaderHook],
      afterResponse: []
    }
  }
  // 生成ky实例
  const instance = ky.create(KyOptions)
  // 发送请求
  return (await instance(requestUrl, { ...options }).json()) as T
}

export default request
